const express=require('express');
const route=express.Router();
const pool=require('../pool')
route.get('/list',(req,res)=>{

  var obj=req.query;
  // 设置默认值
  if(!obj.curPage){
    obj.curPage=1;
  };
  if(!obj.pageSize){
    obj.pageSize=3;
  };
  // 判断有没有typeId
  if(!obj.typeId){obj.typeId=0};
  
  if(obj.typeId==0){ var sql="select count(*) as num from course";}
  else{ var sql="select count(*) as num from course where typeId="+obj.typeId;};
  
  pool.query(sql,(err,result)=>{
    if(err)throw err;
    // 获得总结果数
    let total=result[0].num;
    // 计算总页数
    let pageCount=Math.ceil(total/obj.pageSize);
    // n-1*x,计算每页第一个的数据 5页 15个数据 第二页 每页3个 
    let offset=(obj.curPage-1)*obj.pageSize;
    console.log(result)
    // 执行分页查询
    
    if(obj.typeId==0){
      var sql2=`select * from course,teacher where course.teacherId =teacher.tid limit ${offset},${obj.pageSize} `
    }else{
      var sql2=`select * from course,teacher where course.teacherId =teacher.tid and typeId=${obj.typeId} limit ${offset},${obj.pageSize} `
    }
    pool.query(sql2,(err,result)=>{
      if(err)throw err;
      console.log(result)
      res.json({code:200,msg:"success",data:{list:result,total:total,pageSize:obj.pageSize,curPage:obj.curPage,pageTotal:pageCount}})
    })
  })
})
route.get("/detail", function(req,res){
  var obj = req.query;
  if (!obj.cid) {
    res.json({code:300,msg:"cid is required"});
    return;
  }
  let sql = "SELECT * FROM course,teacher WHERE course.teacherId=teacher.tid AND course.cid="+obj.cid;
  pool.query(sql, (err,result) => {
    if (err) throw err;
    res.json({code:200,msg:"success",data:result[0]});
  })
});
route.get("/newest",(req,res)=>{
  var obj=req.query;
  if(!obj.countNum){obj.countNum=4;}
  let sql="select course.cid,course.title,course.pic,course.price,teacher.tname from course,teacher where course.teacherId=teacher.tid order by cid desc limit "+Number(obj.countNum);
  pool.query(sql,(err,result)=>{
    if(err)throw err;
    res.json({code:200,msg:"succuss",data:result});
  })
})
module.exports=route;